<?php
namespace app\api\logic;
use app\api\BaseModel;
use think\Cache;
use think\Request;
use EasyWeChat\Foundation\Application;
use app\wap\controller\Wechat as WechatCon;
/**
 * Class descript.
 * User: chen guang
 * Date: 2017/11/9 11:22
 */

class Coupon extends \app\api\BaseModel
{
	private $app;
	private $card;
	public function __construct(){
		parent::__construct();
		$this->WechatCon = new WechatCon();//逻辑业务
		$this->app = $this->WechatCon->getApp();//获取实例          
		$this->card = $this->app->card;
	}
	//白名单
	public function white(){
		$usernames = ['qwer3135134', 'zhan11400', 'wen12300w', 'qmzcn792332859'];
		$result = $this->card->setTestWhitelistByUsername($usernames);
	}
	//获取颜色
	public function color(){
		$result = $this->card->getColors();
		return $result;
	}
	//创建卡卷
	public function createCard(){
		$logo = '';
		$files=Request::instance()->file('logo');
		if($files){
			$infos = $files->move(ROOT_PATH . 'public/static/uploads');
			if($infos){
				$logo = request()->domain().'/static/uploads/'.str_replace('\\',"/",$infos->getSaveName());
			}
		}
		$status        = intval($this->requestData['status']);
		$type          = intval($this->requestData['type']);
		$get_limit     = intval($this->requestData['get_limit']);
		$name          = trim($this->requestData['name']);
		$money         = intval($this->requestData['money']);
		$title         = trim($this->requestData['title']);
		$notice        = trim($this->requestData['notice']);
		$des           = trim($this->requestData['des']);
		$start_date    = $this->requestData['start_date'];
		$end_date      = $this->requestData['end_date'];
		$starttime     = strtotime($start_date);
		$endtime       = strtotime($end_date);
		$quantity      = trim($this->requestData['quantity']);
		$service_phone = trim($this->requestData['service_phone']);
		$week          = trim($this->requestData['week']);
		$con = '可用时间：'.date("Y.m.d",$starttime).'-'.date("Y.m.d",$endtime);
		$cardType = 'CASH';
		$baseInfo = [
				'logo_url' => $logo,
				'brand_name' => $name,
				'code_type' => 'CODE_TYPE_QRCODE',
				'title' => $title,
				'sub_title' => $notice,
				'color' => 'Color010',
				'notice' => $notice,
				'service_phone' => $service_phone,
				'description' => $des,
				'date_info' => [
						'type' => 'DATE_TYPE_FIX_TIME_RANGE',
						'begin_timestamp' => $starttime, //开始日期
						'end_timestamp' => $endtime, //结束日期
				],
				'sku' => [
						'quantity' => $quantity, //自定义code时设置库存为0
				],
			//'location_id_list' => ['461907340'],  //获取门店位置poi_id，具备线下门店的商户为必填
				'get_limit' => $get_limit,//每人限领多少
			//'use_limit' => $get_limit,//每人核销数量
				'use_custom_code' => false, //自定义code时必须为true
			//'get_custom_code_mode' => 'GET_CUSTOM_CODE_MODE_DEPOSIT',  //自定义code时设置
				'bind_openid' => false,
				'can_share' => true,            //是否可分享
				'can_give_friend' => true,		//是否赠送
				'center_title' => '立即使用',//顶部居中按钮
				'center_sub_title' => $con,//按钮下方的wording
				'center_url' => 'http://qch.gzldrj.com/qchwap/#/reserve',
				'custom_url_name' => '我的优惠券',
				'custom_url' => 'http://qch.gzldrj.com/qchwap/#/coupon',
				'custom_url_sub_title' => '',
//	        'promotion_url_name' => '更多优惠',
//	        'promotion_url' => 'http://www.qq.com',
				'source' => '七彩虹酒店',
		];
		$especial = [
				'least_cost' => 0,
				'reduce_cost' => $money*100,
		];
		$result = $this->card->create($cardType, $baseInfo, $especial);
		$card_id = $result['card_id'];
		if(!$card_id){
			return array('message'=>'创建失败');
		}
		$data['card_id']          = $card_id;
		$data['logo']             = $logo;
		$data['name']             = $name;
		$data['title']            = $title;
		$data['notice']           = $notice;
		$data['des']              = $des;
		$data['starttime']        = $starttime;
		$data['endtime']          = $endtime;
		$data['create_time']      = time();
		$data['money']            = $money;
		$data['status']           = $status;
		$data['type']             = $type;
		$data['quantity']         = $quantity;
		$data['service_phone']    = $service_phone;
		$data['week']             = $week;
		$data['get_limit']        = $get_limit;
		$insert = db('coupon')->insert($data);
		if(!$insert) return array('message'=>'创建失败');

		$where = array();
		if($type==2){
			$where['type'] = array('gt',1);
		}
		if($type==3){
			$where['type'] = array('gt',2);
		}
		if($type==4){
			$where['type'] = 4;
		}
		$memid = db('member')->where($where)->field('id')->select();
		for ($i=0; $i < count($memid); $i++) {
			$tip['uid'] = $memid[$i]['id'];
			$tip['des'] = '您有可领取的优惠券快去看看吧';
			$tip['image'] = '';
			$tip['status'] = 0;
			$tip['create_time'] = time();
			$tip['type'] = 1;
			$tip['money'] = $money;
			$tip['con'] = $notice;
			db('tip_user')->insert($tip);
		}
		return array();
	}


	//我的优惠券
	public function couponlist(){
		$type = intval($this->requestData['type']);
		$id   = $this->user['id'];
		$member = checkMember($id);
		if(!$member) return array('message'=>'会员不存在');
		$memtype = $member['type'];
		$openid = $member['openid'];
		$cardId = ''; //卡券ID。不填写时默认查询当前appid下的卡券。
		$result = $this->card->getUserCards($openid, $cardId);
		$time=time();
		$arr = array();
//		if($type==1){
//			$status = 'NORMAL';
//		}
//		if($type==2){
//			$status = 'CONSUMED';
//		}
//		if($type==3){
//			$status = 'EXPIRE';
//		}
//		if($type==4){$status = 'DELETE';}if($type==5){$status = 'UNAVAILABLE';}
		if($type==1){
			for ($i=0; $i < count($result['card_list']); $i++) {
				$code         = $result['card_list'][$i]['code'];
				$checkConsume = true;
				$card_id      = $result['card_list'][$i]['card_id'];
				$resultcode   = $this->card->getCode($code, $checkConsume, $card_id);
				if($resultcode['user_card_status']=='NORMAL'){
					$arr[$i]['cardid'] = $card_id;
					$arr[$i]['code']   = $code;
					$detail = $this->card->getCard($card_id);
					$card_type = $detail['card']['card_type'];
					if($card_type=='CASH'){
						$arr[$i]['money']  = $detail['card']['cash']['reduce_cost']/100;
						$arr[$i]['notice'] = $detail['card']['cash']['base_info']['notice'];
						$arr[$i]['title']  = $detail['card']['cash']['base_info']['title'];
						$date_info = $detail['card']['cash']['base_info']['date_info'];
						if($date_info['type']=='DATE_TYPE_FIX_TIME_RANGE'){
							$arr[$i]['starttime'] = date('Y.m.d',$date_info['begin_timestamp']);
							$arr[$i]['endtime']   = date('Y.m.d',$date_info['end_timestamp']);
						}
					}
				}
			}
		}
		if($type==2){
			$coupon = db('order')->where("uid='$id' and (status=2 or status=1) and cart_id!=''")->field("cart_id,code")->select();
			for ($e=0; $e < count($coupon); $e++) {
				$couid = $coupon[$e]['cart_id'];
				$ccd   = $coupon[$e]['code'];
				$find = db('coupon')->where("card_id='$couid'")->find();
				if(!empty($find)){
					$arr[$e]['cardid'] = $couid;
					$arr[$e]['code']   = $ccd;
					$arr[$e]['money']  = $find['money'];
					$arr[$e]['notice'] = $find['notice'];
					$arr[$e]['title']  = $find['title'];
					$arr[$e]['starttime'] = date('Y.m.d',$find['starttime']);
					$arr[$e]['endtime']   = date('Y.m.d',$find['endtime']);
				}else{
					$arr[$e]['cardid'] = '';
					$arr[$e]['code']   = '';
					$arr[$e]['money']  = '';
					$arr[$e]['notice'] = '';
					$arr[$e]['title']  = '';
					$arr[$e]['starttime'] = '';
					$arr[$e]['endtime']   = '';
				}
			}
			$arr = array_filter($arr);
		}
		if($type==3){
			$select = db('coupon')->where("type<='$memtype' and endtime<='$time'")->select();
			for ($y=0; $y < count($select); $y++) {
				$arr[$y]['cardid'] = $select[$y]['card_id'];
				$arr[$y]['code']   = '';
				$arr[$y]['money']  = $select[$y]['money'];
				$arr[$y]['notice'] = $select[$y]['notice'];
				$arr[$y]['title']  = $select[$y]['title'];
				$arr[$y]['starttime'] = date('Y.m.d',$select[$y]['starttime']);
				$arr[$y]['endtime']   = date('Y.m.d',$select[$y]['endtime']);
			}
		}
		$ar['one']   = count($result['card_list']);
		$ar['two']   = db('order')->where("uid='$id' and status=2 and cart_id!=''")->field("cart_id,code")->count();
		$ar['three'] = db('coupon')->where("type<='$memtype' and endtime<='$time'")->count();
		$data['list'] = $arr;
		$data['dat']  = $ar;
		return $data;
	}
	public function check(){
		$id   = $this->user['id'];
		$member = checkMember($id);
		if(!$member) return array('message'=>'会员不存在');
		$card_id  = trim($this->requestData['card_id']);
		$find = db('coupon')->where("card_id='$card_id'")->find();
		$week = $find['week'];
		$time = date('w');
		if($time==0){$date = '星期日';}
		if($time==1){$date = '星期一';}
		if($time==2){$date = '星期二';}
		if($time==3){$date = '星期三';}
		if($time==4){$date = '星期四';}
		if($time==5){$date = '星期五';}
		if($time==6){$date = '星期六';}
		if(!strstr($week,$date)) return array('message'=>'优惠券使用日期不正确');
		return array();
	}
	//核销
	public function deletecoupon($code,$card){;
		$res=$this->card->consume($code, $card);
		return array();
	}


	//领券中心
	public function cardlist(){
		$id   = $this->user['id'];
		$time = time();
		$member = checkMember($id);
		if(!$member) return array('message'=>'会员不存在');
		$type = $member['type'];
		$where['deletes'] = 1;
		$where['endtime'] = array('gt',$time);
		if($type==1){
			$where['type'] = 1;
		}
		if($type==2){
		//	$where['type'] = array(array(1,2),'or');
			$where['type'] = array('between',[1,2]);
		}
		if($type==3){
			$where['type'] = array('neq',4);
		}
		if($type==4){
			$where['type'] = array('neq',0);
		}
		$background = db('background')->where("id=1")->find();
		$list = db('coupon')->where($where)->field('id,card_id,logo')->order('id desc')->limit(10)->select();
		if(empty($list)) return array('message'=>'该会员没有可领取的卡券');
		$banner     = IMG_PATH.$background['images'];
		$pageTitle = '七彩虹优惠券';
		$canShare  = true;
		//SCENE_NEAR_BY          附近
		//SCENE_MENU             自定义菜单
		//SCENE_QRCODE             二维码
		//SCENE_ARTICLE             公众号文章
		//SCENE_H5                 h5页面
		//SCENE_IVR                 自动回复
		//SCENE_CARD_CUSTOM_CELL 卡券自定义cell
		$card = array();
		foreach ($list as $k => $val) {
			$card[$k]['card_id']   = $val['card_id'];
			$card[$k]['thumb_url'] = $val['logo'];
		}
		$scene = 'SCENE_H5';
		$result = $this->card->createLandingPage($banner, $pageTitle, $canShare, $scene, $card);

		$data['url'] = $result;
		return $data;
	}

	public function jsCard()
	{
		$cards = [
				['card_id' => 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY', 'outer_id' => 2],
				['card_id' => 'pdkJ9uJ37aU-tyRj4_grs8S45k1c', 'outer_id' => 3],
		];
		return  $this->card->jsConfigForAssign($cards); // 返回 json 格式
	}

	//优惠券详情
	public function detail()
	{
		$uid   = $this->user['id'];
		$id = trim($this->requestData['id']);
		$member = checkMember($uid);
		if(!$member) return array('message'=>'会员不存在');
		$find = db('coupon')->where("card_id='$id'")->find();
		if(!$find) return array('message'=>'优惠券不存在');
		$money = $find['money'];
		$status = $find['status'];
		$data['id'] = $find['id'];
		$data['title'] = $find['name'];
		$data['name'] = $money.'元优惠券';
		$con='';
		if($status==1){
			$con = '减免房费'.$money.'元';
		}
		if($status==2){
			$con = '减免游泳费'.$money.'元';
		}
		if($status==3){
			$con = '减免健身费'.$money.'元';
		}
		$data['des'] = $con;
		$data['starttime'] = date("Y.m.d",$find['starttime']);
		$data['endtime']   = date("Y.m.d",$find['endtime']);
		$data['money'] = $find['money'];
		$data['week'] = $find['week'];
		$data['service_phone'] = $find['service_phone'];
		return $data;
	}
	//微信优惠券详情
	public function wxdetail(){
		$cardId = 'pXkLask3hgc8_cNiCmW2i65IsCQ8';
		$result = $this->card->getCard($cardId);
		$data['list'] = $result;
		return $data;
	}
	//删除卡券
	public function delcoupon(){
		$id = input('id/d');
		$find = db('coupon')->where("id='$id'")->find();
		$data['deletes']=0;
		db('coupon')->where("id='$id'")->update($data);
		$cardId = $find['card_id'];
		$result = $this->card->delete($cardId);
		if($result['errcode']!=0) return array('message'=>'删除失败');
		return array();
	}

	/*
	 * 创建会员卡
	 */
	public function createMemberCard(){
		$starttime     = strtotime(date('2017-12-05'));
		$endtime       = strtotime(date('2017-12-30'));
		$cardType = 'MEMBER_CARD';
		$baseInfo = array(
				"logo_url"=> "https://mmbiz.qlogo.cn/mmbiz_jpg/qKh7VeSReD3hlPco3ty9P8ibPMiaXTWnH95BLTn14hWIUvVvSjFtCQV6eW9MpCia8ic8cnw3mLFicSeQZ1diaBNMia6wA/0?wx_fmt=jpeg",
				"brand_name"=> "海底捞",
				"code_type"=>"CODE_TYPE_TEXT",
				"title"=> "海底捞会员卡",
				"color"=>"Color010",
				"notice"=> "使用时向服务员出示此券",
				"service_phone"=> "020-88888888",
				"description"=> "不可与其他优惠同享",
				"date_info"=>array(
						"type"=>"DATE_TYPE_PERMANENT"
				),
				"sku"=>array(
						"quantity"=> 50000000
				),
				"get_limit"=>1,
				"use_custom_code"=> false,
				"can_give_friend"=>true,

				"custom_url_name"=> "立即使用",
				"custom_url"=>"http://weixin.qq.com",
				"custom_url_sub_title"=>"6个汉字tips",
				"promotion_url_name"=>"营销入口1",
				"promotion_url"=>"http://www.qq.com",
				"need_push_on_view"=> true,
		);
		$especial = [
				'supply_bonus' => false,
				'supply_balance'=>false,
				'prerogative' => '22222',
				'auto_activate'=>true,
				'background_pic_url'=>'http://mmbiz.qpic.cn/mmbiz_png/qKh7VeSReD1DdFzdpAaaA0ngmvah1goBiafAbI08R8ntmwN5Tn4UxGx9l5aXgwDWyVw33ibOmsXmPK1Dibdica52yg/0?wx_fmt=png',
			//'tips'=>'222',
			//'url'=>'http://www.baidu.com',
		];
		//var_dump($this->card);exit;
		$result = $this->card->create($cardType, $baseInfo, $especial);
		$card_id = $result['card_id'];
		if(!$card_id){
			return array('message'=>'创建失败');
		}
		return array();
	}

	//领取
	public function getpage() {
		//1为银卡会员2金卡会员3铂金卡会员4黑金卡会员
		$member=checkMember($this->user['id']);
		if($member['type']==1){
			$card=db("config")->where("id=5")->find();
		}
		if($member['type']==2){
			$card=db("config")->where("id=6")->find();
		}
		if($member['type']==3){
			$card=db("config")->where("id=7")->find();
		}
		if($member['type']==4){
			$card=db("config")->where("id=8")->find();
		}
		$apiTicket = $this->card->getApiTicket();
		// 注意 URL 一定要动态获取，不能 hardcode.（获取当前网页的url）
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		//时间戳
		$timestamp = time();
		//随机字符串获取
		// $nonceStr = $this->createNonceStr();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = $timestamp.$apiTicket.$card['value'];//"pfFVE0x87nEaSXp5iojDMMNX92sw";
		//生成字符串是用来签名用的
		$signature = sha1($string);

		$signPackage = array(
				"timestamp" => $timestamp,
				"signature" => $signature,
				"card_id" => $card['value'],
		);
		return $signPackage;
	}

//使用会员卡领取的签名包
	public function getHuiYuanSignPackage() {
		//1为银卡会员2金卡会员3铂金卡会员4黑金卡会员
		if($this->user['type']==1){
			$card=db("config")->where("id=5")->find();
		}
		if($this->user['type']==2){
			$card=db("config")->where("id=6")->find();
		}
		if($this->user['type']==3){
			$card=db("config")->where("id=7")->find();
		}
		if($this->user['type']==4){
			$card=db("config")->where("id=8")->find();
		}
		$cardid=$card['value'];
		$apiTicket = $this->card->getApiTicket();
		// 注意 URL 一定要动态获取，不能 hardcode.（获取当前网页的url）
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		//时间戳
		$timestamp = time();
		//随机字符串获取
		// $nonceStr = $this->createNonceStr();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = $timestamp.$apiTicket.$card['value'];//"pfFVE0x87nEaSXp5iojDMMNX92sw";
		//生成字符串是用来签名用的
		$signature = sha1($string);

		$openid=$this->user['openid'];
		$cardId=$card['value'];
		$result = $this->card->getUserCards($openid, $cardId);
		$arr=$result->card_list;

		//var_dump($arr);
		if($arr){
			$a=0;
		}else{
			$a=0;
		}
		$signPackage = array(
				"status" => $a,
				"timestamp" => $timestamp,
				"signature" => $signature,
				"card_id" => $card['value'],
		);
		return $signPackage;
	}
	//调用js-sdk的签名包
	public function getSignPackage() {
		$jsapiTicket =$this->app->js->ticket();
		// 注意 URL 一定要动态获取，不能 hardcode.（获取当前网页的url）
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url ="$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		//时间戳
		$timestamp = time();
		//随机字符串获取
		$nonceStr = md5(time());
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		//生成字符串是用来签名用的
		$signature = sha1($string);
		$signPackage = array(
				"appId"  => config('wx.app_id'),
				"nonceStr" => $nonceStr,
				"timestamp" => $timestamp,
			//"url"  => $url,
				"signature" => $signature,
			//"rawString" => $string
		);
		return $signPackage;
	}
}